﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MShop.Core.DataAccess;
using MShop.Core.Domain;
using MShop.Core;
using MShop.Web.Components.Paging;
using MShop.Core.Util;
using MShop.Web.Components.Util;

namespace MShop.Web.Controllers
{
    public class ProductController : ControllerBase
    {
        private readonly IProductDao _ProductDao;
        private readonly IItemCatDao _ItemCatDao;
        private readonly ISupplierDao _SupplierDao;
        private readonly IBrandDao _BrandDao;
        private readonly ICommonDao<ProductComment> _ProductCommentDao;
        private readonly ICartItemDao _CommonDao;
        private readonly IShopContext _IShopContext;
        private readonly IDictDao _DictDao;
        private readonly  IShopUsersFavDao _CommonDao2;
        public ProductController(IProductDao productDao, IItemCatDao itemcatdao, IBrandDao brandDao, ISupplierDao supplierDao,
            ICartItemDao commonDao, IShopContext shopContext, IDictDao dictDao, IShopUsersFavDao commonDao2,ICommonDao<ProductComment> _productCommentDao)
        { 
            _ItemCatDao = itemcatdao;
            _ProductDao = productDao;
            _BrandDao = brandDao;
            _SupplierDao = supplierDao;
            _CommonDao = commonDao;
            _IShopContext = shopContext;
            _DictDao = dictDao;
            _CommonDao2 = commonDao2;
            _ProductCommentDao = _productCommentDao;
        }

        public ActionResult Index(int? page,int? cid,decimal? minprice,decimal? maxprice,int? region)
        {
            AppendMeta("产品中心","进口红酒,葡萄酒","产品中心可以选购各种产品");
            var q = _ProductDao.GetProducts(cid, minprice, maxprice, region);
            q= q.OrderBy(x=>x.Sort);
            int index=0;
            if(page.HasValue)
            {
                index = page.Value-1;
            }          


            ViewData["cids"] = _ItemCatDao.GetAll();
            ViewData["regions"]= _DictDao.GetByTypeId(1);
            PagedList<Product> pagedlist = new PagedList<Product>(q, index, _IShopContext.Settings.WebSitePageSize);
            return View(pagedlist);          
        }


        public ActionResult RecommendProduct()
        {
            var q = _ProductDao.Find(x => x.IsPublish && x.IsDelete == false && x.Status==1).OrderBy(x => x.Sort).Take(4);
            return PartialView("product/RecommendProduct",q);
        }

        public ActionResult TopProduct()
        {
            var q = _ProductDao.Find(x => x.IsRecommend &&  x.IsPublish && x.IsDelete == false && x.Status==1).OrderByDescending(x => x.Click).Take(4);
            return PartialView("product/TopProduct", q);
        }

        

        //public ActionResult MyCart()
        //{
        //    AppendMeta("我的购物车");
        //    if (User.Identity.IsAuthenticated)
        //    {
        //        return View(_CommonDao.Find(x => x.UserId == _IShopContext.CurrentUser.UserId));
        //    }
        //    else
        //    {
        //        return View(_CommonDao.Find(x => x.SessionId == _IShopContext.SessionId));
        //    }
        //}
        public ActionResult AddComment()
        {
            ProductComment pc = new ProductComment();
            HttpCookie cookie=Request.Cookies["CheckCode"];
            #region"支持cookie"
            if (cookie != null)
            {
                if (Request.Form["checkcode"].ToLower() == cookie.Value.ToString().ToLower())
                {

                    try
                    {
                        int id = int.Parse(Request.Params["productid"]);
                        Product p = _ProductDao.GetById(id);                       
                       
                        string comment = Text.TruncateHtml(Request.Params["comment"]);
                        pc.Comment = Text.TruncateText(comment, 200);
                      
                        pc.Star = Convert.ToInt32(Request.Params["star"]);
                        if (!string.IsNullOrEmpty(Request.Params["userid"]))
                        {
                            pc.UserId = new Guid(Request.Params["userid"]);
                        }
                        pc.UserName = Request.Params["username"];
                        pc.ProductType = "1";
                        pc.ProductName = p.ProductName;
                        pc.ProductImageUrl = p.ImageUrl;
                        pc.IsAnomymous = pc.UserId.HasValue ? false : true;
                        pc.ProductId = p.Id;
                        _ProductCommentDao.Save(pc);
                        _ProductCommentDao.SaveChanges();
                        return Json(new { UserName = pc.UserName, Comment = pc.Comment, JsonType = pc.JsonType, Star = pc.Star },JsonRequestBehavior.AllowGet);
                    }
                    catch
                    {
                        pc.JsonType = "4";
                        return Json(new { UserName = pc.UserName, Comment = pc.Comment, JsonType = pc.JsonType, Star = pc.Star }, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    pc.JsonType="2";
                    return Json(new { UserName = pc.UserName, Comment = pc.Comment, JsonType = pc.JsonType, Star = pc.Star }, JsonRequestBehavior.AllowGet);
                }
            }
            #endregion
            else
            {
                pc.JsonType = "1";
                return Json(new { UserName = pc.UserName, Comment = pc.Comment, JsonType = pc.JsonType, Star = pc.Star }, JsonRequestBehavior.AllowGet);
            }
            
        }
              
        public ActionResult AddToFav(int id)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Content("-1");
            }
            try
            {
                string result = _CommonDao2.UpdateFav(_IShopContext.CurrentUser.UserId, id).ToString();
                _CommonDao2.SaveChanges();
                return Content(result);
            }
            catch
            {
                return Content("-100");
            }            
        }

       [OutputCache(Duration = 120, VaryByParam = "Id", Location = System.Web.UI.OutputCacheLocation.Server)]
        public ActionResult Item(int id)
        {
            Product p = _ProductDao.GetById(id);
            string description = string.IsNullOrEmpty(p.Description) ? p.Desc : p.Description;
            if (!string.IsNullOrEmpty(description))
            {
                description = Text.TruncateHtml(description);
                description = Text.TruncateText(description, 120);
            }
            AppendMeta(string.Concat(p.ProductName,"-",p.ItemCat.Name),string.IsNullOrEmpty(p.Keywords)?string.Concat(p.ProductName,",",p.ItemCat.Name):p.Keywords,
                description
                );
            p.Click++;
            _ProductDao.SaveChanges();
           
            return View(p);
        }

       [OutputCache(Duration = 60, VaryByParam = "Id", Location = System.Web.UI.OutputCacheLocation.Server)]
        public ActionResult ProductComment(int id)
        {
            ProductComment[] pc = _ProductCommentDao.Find(x=>x.ProductId==id).OrderByDescending(x => x.Id).Take(50).ToArray();
            
            return PartialView(pc);
        }


        public ActionResult CreateCheckCodeImage()
        {
            string code = Utils.GenerateCheckCode();
           // Session["CheckCode"] = code;
            HttpCookie cookie=new HttpCookie("CheckCode", code);
            Response.AppendCookie(cookie);
            byte[] bytes = Utils.CreateCheckCodeImage(code);
            return File(bytes, "image/Gif");
        }


        [HttpPost]
        public ActionResult Item(int id,int quanitiy,string skuid)
        {
            Product product = _ProductDao.GetById(id);
            if (User.Identity.IsAuthenticated)
            {

                CartItem cartitem = new CartItem();
                cartitem.ProductId = product.Id;
                cartitem.Price = product.ShopPrice;
                cartitem.Quanitiy = quanitiy;
                cartitem.UserId = _IShopContext.CurrentUser.UserId;
                cartitem.SkuId = skuid;
                cartitem.Point = product.Points;
                cartitem.PicUrl = product.PicUrl;
                if (!string.IsNullOrEmpty(skuid))
                {
                    cartitem.ProductName = string.Concat(product.ProductName, "-", skuid);
                }
                else
                {
                    cartitem.ProductName = product.ProductName;
                }
                cartitem.IsAnomymous = false;
                _CommonDao.Save(cartitem);
                _CommonDao.SaveChanges();

              
            }
            else
            {
                string SessionId = string.Empty;
                HttpCookie cookie = Request.Cookies["SessionId"];
                if (cookie == null)
                {
                    cookie = new HttpCookie("SessionId", Session.SessionID);                   
                    Response.AppendCookie(cookie);
                    SessionId = Session.SessionID;
                }
                else
                {
                    SessionId = cookie.Value;
                }
                CartItem cartitem = new CartItem();
                cartitem.ProductId = product.Id;
                cartitem.Price = product.ShopPrice;
                cartitem.Quanitiy = quanitiy;
                cartitem.SessionId = SessionId;
                cartitem.SkuId = skuid;
                cartitem.Point = product.Points;
                cartitem.PicUrl = product.PicUrl;
                if (!string.IsNullOrEmpty(skuid))
                {
                    cartitem.ProductName = string.Concat(product.ProductName, "-", skuid);
                }
                else
                {
                    cartitem.ProductName = product.ProductName;
                }
                cartitem.IsAnomymous = true;
                _CommonDao.Save(cartitem);
                _CommonDao.SaveChanges();
            }

            return RedirectToAction("mycart","trade");
        }
    }
}
